package com.zilla.android.zillacore.libzilla.db;

import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import com.github.snowdream.android.util.Log;
import com.zilla.android.zillacore.libzilla.file.FileHelper;

import java.util.ArrayList;

/**
 * 数据库基础类，处理数据库的创建和升级
 *
 * @author ze.chen
 */
public final class DBHelper extends SQLiteOpenHelper {

    private static DBHelper helper = null;
    private DBUpgradeListener dbUpgradeListener;

    /**
     * 数据库名称
     */
    private DBHelper(Context context, String name, CursorFactory factory,
                     int version) {
        super(context, name, factory, version);
    }

    public static DBHelper getInstance() {
        return helper;
    }

    /**
     * 系统初始化时构造
     *
     * @param app
     * @param dbName
     * @param version
     */
    public static void init(Application app, String dbName, int version) {
        helper = new DBHelper(app, dbName, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        if (dbUpgradeListener != null) {
            dbUpgradeListener.onCreate(db);
        }
    }

    /**
     * 数据库升级时，根据配置文件中的配置信息进行升级，可以涉及到添加字段,具体升级配置在res/raw/system.properties文件中定义
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        executeLocalSQL(db);
        if (dbUpgradeListener != null) {
            dbUpgradeListener.onUpgrade(db, oldVersion, newVersion);
        }
    }

    public DBUpgradeListener getDbUpgradeListener() {
        return dbUpgradeListener;
    }

    public void setDbUpgradeListener(DBUpgradeListener dbUpgradeListener) {
        this.dbUpgradeListener = dbUpgradeListener;
    }

    /**
     * 数据库初始化和升级回调接口
     */
    public interface DBUpgradeListener {
        void onCreate(SQLiteDatabase db);

        void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
    }

    /**
     * @return void
     * @Title: executeLocalSQL
     * @Description: 执行本地SQL语句
     */
    private void executeLocalSQL(SQLiteDatabase db) {
        ArrayList<String> sqlList = FileHelper.getUpgradeSqls();
        for (int i = 0, l = sqlList.size(); i < l; i++) {
            try {
                db.execSQL(sqlList.get(i));
            } catch (Exception e) {
                Log.e(e.getMessage());
            }
        }
    }
}
